﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Text.RegularExpressions;
using QD.Utill;
using QD.Snapshot.Core.Config;
using NSoup.Nodes;
using NSoup.Select;
using System.Net;

namespace QD.Snapshot.Core.BLL
{
    public class Search_Sogou : SearchBase
    {
        static string SNUID = "";
        static string SUV = "";

        public Search_Sogou(TextBox textBox, int SleepTime)
        {
            this.textBox = textBox;
            this.SleepTime = SleepTime;
            this.copyform = "2";        //搜狗搜索引擎
            Echo("搜狗截图已启动");
        }


        public HttpRequest Http = new HttpRequest();
        string html;
        Model.TaskModel_360 taskModel = new Model.TaskModel_360();
        public override void Search(string keyword, Model.Product product, Model.WebSite company)
        {
            Thread.Sleep(SleepTime);
            InitSUV();
            html = Search(keyword); //搜索

            if (IsCode_Sogou)
            {
                EchoCodeLog(EngineType.SoGou, "搜狗出现验证码");
                RemoveCode();
            }
            else
            {
                Echo(string.Format("搜索 {0}", keyword));
            }

            taskModel.itemid = product.itemid;
            taskModel.keyword = keyword;
            taskModel.company = company;
            taskModel.html = html;

            NumHelper.Instance.SetNumSoGou(1);    //统计搜索速度
            ThreadPool.QueueUserWorkItem(new WaitCallback(CheckOrAdd), taskModel);
        }

        void CheckOrAdd(object obj)
        {
            Model.TaskModel_360 model = obj as Model.TaskModel_360;
            model.html = Regex.Replace(model.html, "<!--([\\s\\S].*?)-->", "");

            CheckOrAdd(model.html, model.keyword, model.itemid, model.company);
        }

        void CheckOrAdd(string html, string keyword, int itemid, Model.WebSite company)
        {
            NSoup.Nodes.Document doc = NSoup.NSoupClient.Parse(html);
            Regex r1 = new Regex(FixRegex(company.ShortName), RegexOptions.IgnoreCase);
            Regex SiteName = new Regex(FixRegex(company.SiteName), RegexOptions.IgnoreCase);
            Regex Cellphone = new Regex(FixRegex(company.Cellphone), RegexOptions.IgnoreCase);
            Regex phone = new Regex(FixRegex(company.Phone), RegexOptions.IgnoreCase);

            CheckOrAdd(doc, r1, SiteName, Cellphone, phone, itemid, company.UserID, keyword);
        }

        private readonly object obj = new object();
        Model.Snap snapModel = new Model.Snap();
        void CheckOrAdd(Document doc, Regex r1, Regex SiteName, Regex Cellphone, Regex phone, int itemid, int userid, string keyword, int page = 1)
        {
            NSoup.Nodes.Element parent = doc.GetElementById("main");
            if (parent == null) return;

            NSoup.Select.Elements result = parent.Select(".results > div"); //直接的下级DIV
            if (result == null) return;

            HideElement(doc.GetElementById("common_qc_container"));         //顶部广告
            HideElement(doc.GetElementById("promotion_adv_container"));     //顶部广告
            HideElement(doc.GetElementById("right"));                       //清空右侧的图片和排名
            HideElement(doc.GetElementById("leftbottomleadContainer"));     //清空推广信息
            HideElement(doc.GetElementById("ui-vr-height"));                //清空 阿里巴巴等图片列表            
            HideElement(doc.GetElementById("vr2122-list"));                 //清空 搜狗购物图片

            HideElementList(doc.GetElementsByClass("vr-map151014"));        //清空 搜狗地图
            HideElementList(parent.GetElementsByClass("pic-list"));         //清空 搜狗新闻图片
            HideElementList(doc.GetElementsByClass("fig-tv-table"));        //清空 搜狗视频
            HideElementList(doc.GetElementsByClass("umbrella-list"));       //清空 阿里巴巴推荐
            HideElementList(parent.GetElementsByClass("str_img"));
            parent.GetElementsByClass("r-sech").Remove();       //清空推荐框


            int index = 0;
            bool isFirst = true;
            string nums_html = "";
            foreach (Element ele in result)
            {
                HideElement(doc.GetElementById("sogou_vr_70035201_wrap_" + index));     //清空 3C产品排行
                HideElement(doc.GetElementById("sogou_vr_10000103_piclist_" + index));  //清空 搜狗图片
                HideElement(doc.GetElementById("sogou_vr_70071201_software_" + index)); //清空 搜狗下载
                HideElement(doc.GetElementById("sogou_vr_70074601_aggrBox2_" + index)); //清空 搜狗影视  
                HideElement(doc.GetElementById("sogou_vr_30000909_sq_ext_" + index)); //清空 推荐

                if (ele.Attributes["class"] != "rb" && ele.Attributes["class"] != "vrwrap")
                    continue;

                index++;
                if (r1.IsMatch(ele.Text()) || CheckShortNameList(ele.Text()) || CheckQJY(ele.Text(), SiteName, Cellphone, phone))
                {
                    string index_key = GetMd5(ele.GetElementsByTag("h3").Text); //第几行的key,更新时，用来确定更新哪一行
                    string platform = GetPlatform(ele.Text());                  //上词的平台

                    if (isFirst)
                    {
                        RemoveAttr(result);
                        nums_html = "<span id='sp_nums' class='sp_nums' data='" + parent.Select(".num-tips").Text + "'></span>";
                        isFirst = false;
                    }

                    //添加成功记录
                    lock (obj)
                    {
                        snapModel.itemid = itemid;
                        snapModel.userid = userid;
                        snapModel.keyword = keyword;
                        snapModel.ranking = index;
                        snapModel.copyform = Convert.ToInt32(copyform);
                        snapModel.page = page;
                        snapModel.state = 0;
                        snapModel.clientid = SiteConfig.ClientId;
                        snapModel.platform = platform;
                        snapModel.updatetime = DateTime.Now;
                        snapModel.index_key = index_key;
                        snapModel.html = result.OuterHtml() + nums_html;
                        AddSnap(snapModel);
                        BLL.File.Snap.AddSnap(snapModel);
                    }
                }
            }
        }

        protected override void RemoveAttr(Elements result)
        {
            Elements ele = result.Select("a");
            ele.Attr("href", "#");
            ele.RemoveAttr("target");
            ele.RemoveAttr("name");
            ele.RemoveAttr("onclick");
            ele.RemoveAttr("cachestrategy");
            ele.RemoveAttr("sogou_preview_link");
            ele.RemoveAttr("sogou_preview_title");
            ele.RemoveAttr("url");
            ele.RemoveAttr("id");

            Elements span = result.Select("span");
            span.RemoveAttr("zanurl");
            span.RemoveAttr("zantitle");
            span.RemoveAttr("zandocid");
            span.RemoveAttr("id");

            Elements cite = result.Select("cite");
            cite.RemoveAttr("id");

            Elements style = result.Select("style");   //清空 script模板
            style.Remove();

            Elements script = result.Select("script");   //清空 script模板
            script.Remove();

            Elements nums = result.Select(".sp_nums");  //计数的文字
            nums.Remove();
        }

        /// <summary>
        /// 删除验证码
        /// </summary>
        void RemoveCode()
        {
            int maxCount = 20;
            for (var i = 0; i < maxCount; i++)
            {
                InitSUV();
                Search(new Random().Next().ToString());

                if (!IsCode_Sogou)
                    break;
                else
                {
                    SNUID = string.Empty;
                    Echo("出现验证码，正在重试");
                }
            }
        }

        /// <summary>
        /// 搜索
        /// </summary>
        string Search(string keyword)
        {
            Http.AddCookie("SNUID", SNUID, ".sogou.com", DateTime.Now.AddYears(1));
            Http.AddCookie("SUV", SUV, ".sogou.com", DateTime.Now.AddMonths(1));
            Http.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
            Http.Referer = Engine.URL_SOGOU;

            var html = Http.Requset(string.Format(Engine.URL_SOGOU, keyword));
            AppendParam(Http.m_Cookie);       //追加cookie
            IsCode_Sogou = CheckCode(html);   //是否出现验证码
            return html;
        }
        /// <summary>
        /// 初始化 SUV 参数
        /// </summary>
        void InitSUV()
        {
            if (!IsCode_Sogou) return;
            try
            {
                Dictionary<string, object> dic = BLL.SnapToken.GetBySogou();
                if (dic != null)
                {
                    SUV = Convert.ToString(dic["SUV"]);
                }
            }
            catch { }
        }

        void AppendParam(CookieContainer cookieContainer)
        {
            var cookieList = cookieContainer.GetCookies(new Uri(Engine.URL_SOGOU));
            foreach (Cookie cookie in cookieList)
            {
                if (cookie.Name == "SNUID")
                    SNUID = cookie.Value;

                if (cookie.Name == "SUV")
                    SUV = cookie.Value;
            }
        }
    }
}